package com.catazy.module_collect.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.catazy.module_collect.repository.CollectRepository
import com.catazy.wanandroid.common_base.bus.BusKey
import com.catazy.wanandroid.common_base.bus.LiveDataBus
import com.catazy.wanandroid.common_base.constants.Constants.CollectType.UNKNOWN
import com.catazy.wanandroid.common_base.event.MessageEvent
import com.catazy.wanandroid.common_base.ext.USER_NOT_LOGIN
import com.catazy.wanandroid.common_base.ext.logE
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * 作者: Tao
 * 日期: 2024/4/15
 * 时间: 10:07
 * 描述:
 */
class CollectViewModel(private val repository: CollectRepository) : ViewModel() {

    /**
     * 收藏文章
     */
    fun collectArticle(indexPage: Int, position: Int, id: Int) {
        viewModelScope.launch {
            repository.collectArticle(id)
                .catch {
                    logE(TAG, it.message, it)
                }
                .collectLatest {
                    val event = if (it.errorCode == USER_NOT_LOGIN) {
                        MessageEvent(indexPage, UNKNOWN, position, id)
                    } else {
                        MessageEvent(indexPage, COLLECT, position, id)
                    }
                    LiveDataBus.get().with(BusKey.COLLECT).value = event
                }
        }
    }

    /**
     * 取消收藏文章
     */
    fun unCollectArticle(indexPage: Int, position: Int, id: Int) {
        viewModelScope.launch {
            repository.unCollectArticle(id)
                .catch {
                    logE(TAG, it.message, it)
                }
                .collectLatest {
                    // 未登录，发送未登录事件
                    val event = if (it.errorCode == USER_NOT_LOGIN) {
                        MessageEvent(indexPage, UNKNOWN, position, id)
                    } else {
                        MessageEvent(indexPage, UNCOLLECT, position, id)
                    }
                    LiveDataBus.get().with(BusKey.COLLECT).value = event
                }
        }
    }

    companion object {
        private const val TAG = "CollectViewModel"
        const val COLLECT = "COLLECT"
        const val UNCOLLECT = "UNCOLLECT"
    }
}